package com.mallbook.controller.servlet.admin;

import com.mallbook.controller.servlet.front.UserServlet;
import com.mallbook.model.exception.*;
import com.mallbook.model.pojo.Admin;
import com.mallbook.model.pojo.PageBean;
import com.mallbook.model.pojo.User;
import com.mallbook.model.service.AdminService;
import com.mallbook.model.utils.MallDefaultConfig;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author 宋明松
 * @Version V1.0.0
 * @Date 2022-07-08
 */
@WebServlet("/admin/manager")
public class ManagerServlet extends HttpServlet {
    private AdminService adminService = new AdminService();
    private static final Logger logger = LoggerFactory.getLogger(ManagerServlet.class);


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String opr = req.getParameter("opr");
        if (opr == null) {
            req.getRequestDispatcher("/WEB-INF/admin/login.jsp").forward(req, resp);
        } else if (opr.equals("initManager")) {
            doInitManager(req, resp);
        } else if (opr.equals("updateSelect")) {
            doUpdateSelect(req, resp);
        } else if (opr.equals("del")) {
            doDel(req, resp);
        } else if (opr.equals("shield")) {
            doShield(req, resp);
        } else if (opr.equals("update")) {
            doUpdate(req, resp);
        } else if (opr.equals("add")) {
            doAdd(req, resp);
        } else if (opr.equals("check")) {
            doCheck(req, resp);
        }
    }

    /**
     * 检查账号信息
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doCheck(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        JSONObject json = new JSONObject();
        String name = req.getParameter("account");
        try {
            adminService.checkInfo(name);
            json.put("msg", "ok");
            resp.getWriter().print(json);
            resp.getWriter().close();
        } catch (AccountExitsException e) {
            json.put("msg", "账号已存在");
            resp.getWriter().print(json);
            resp.getWriter().close();
        }
    }

    /**
     * 添加管理员
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void doAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String name = req.getParameter("account");
        String pwd = req.getParameter("password");
        String power = req.getParameter("power");
        String state = req.getParameter("state");
        String manager = null;
        if (name != null && !name.isEmpty()) {
            manager = new String(name.getBytes("iso8859-1"), StandardCharsets.UTF_8);
        }
        JSONObject json = new JSONObject();
        if (power == null || power.isEmpty()) {
            json.put("msg", "用户权限不能为空");
            resp.getWriter().print(json);
            resp.getWriter().close();
            return;
        }
        if (pwd == null || pwd.isEmpty()) {
            json.put("msg", "用户密码不能为空");
            resp.getWriter().print(json);
            resp.getWriter().close();
            return;
        }
        if (state == null || state.isEmpty()) {
            json.put("msg", "用户状态不能为空");
            resp.getWriter().print(json);
            resp.getWriter().close();
            return;
        }
        try {
            adminService.register(manager, pwd, power, Integer.parseInt(state));
            json.put("msg", "ok");
            resp.getWriter().print(json);
            resp.getWriter().close();
//            resp.sendRedirect("/admin/manager?opr=initManager&p=1");
        } catch (ServiceException e) {
            e.printStackTrace();
            json.put("msg", "系统维护中");
            resp.getWriter().print(json);
            resp.getWriter().close();
        }
    }

    /**
     * 修改数据
     *
     * @param req
     * @param resp
     */
    private void doUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        String uid = req.getParameter("uid");
        String lastIp = req.getParameter("lastIp");
        String times = req.getParameter("times");
        String state = req.getParameter("state");
        String power = req.getParameter("power");
        logger.info("修改后的权限{}", power);
        JSONObject json = new JSONObject();
        if (power.isEmpty()) {
            json.put("msg", "用户权限不能为空");
            resp.getWriter().print(json);
            resp.getWriter().close();
            return;
        }
        if (state.isEmpty()) {
            json.put("msg", "用户状态不能为空");
            resp.getWriter().print(json);
            resp.getWriter().close();
            return;
        }
        try {
            adminService.updateUser(null, power, times, Integer.parseInt(state), lastIp, Integer.parseInt(uid));
            json.put("msg", "ok");
            resp.getWriter().print(json);
            resp.getWriter().close();
        } catch (ServiceException e) {
            e.printStackTrace();
            json.put("msg", "系统维护中");
            resp.getWriter().print(json);
            resp.getWriter().close();
        }

//        resp.sendRedirect("/admin/manager?opr=initManager&p=1");
    }

    private void doShield(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        String state = req.getParameter("state");
        try {
            adminService.disableUser(Integer.parseInt(id), Integer.parseInt(state));
        } catch (ServiceException e) {
            e.printStackTrace();
            System.out.println("系统维护中");
        }
        resp.sendRedirect("/admin/manager?opr=initManager&p=1");
    }

    private void doDel(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        try {
            adminService.delUser(Integer.parseInt(id));
        } catch (ServiceException e) {
            e.printStackTrace();
            System.out.println("系统维护中");
        }
        resp.sendRedirect("/admin/manager?opr=initManager&p=1");
    }

    private void doInitManager(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String p = req.getParameter("p");
        String pSize = req.getParameter("pSize");
        String state = req.getParameter("state");
        String name = req.getParameter("name");
        String startTime = req.getParameter("startTime");
        String endTime = req.getParameter("endTime");
        String lastIp = req.getParameter("lastIp");
        String power = req.getParameter("power");
        Admin admin = new Admin();
        if (state != null && !state.equals("0")) {
            admin.setState(Integer.parseInt(state));
        }
        if (power != null && !power.equals("0")) {
            admin.setPower(power);
        }
        if (name == null || name.isEmpty()) {
            name = null;
        }
        if (startTime == null || startTime.isEmpty()) {
            startTime = null;
        }
        if (endTime == null || endTime.isEmpty()) {
            endTime = null;
        }
        admin.setUsername(name);
        admin.setStartTime(startTime);
        admin.setEndTime(endTime);
        admin.setLastIP(lastIp);

        if (pSize != null && !pSize.isEmpty()) {
            MallDefaultConfig.USER_PAGE_SIZE = Integer.parseInt(pSize);
        } else {
            MallDefaultConfig.USER_PAGE_SIZE = 5;
        }

        Integer page = null;
        if (p == null || p.equals("")) {
            page = 1;
        } else {
            page = Integer.parseInt(p);
        }

        try {
            PageBean<Admin> adminPageBean = adminService.getUsersByCondition(admin, page);
            req.setAttribute("pageBean", adminPageBean);
            req.setAttribute("seachUser", admin);
        } catch (ServiceException e) {
            e.printStackTrace();
            System.out.println("系统维护中");
        }
        req.getRequestDispatcher("/WEB-INF/admin/manager_list.jsp").forward(req, resp);
    }

    /**
     * 查询需要修改的数据展示到弹窗
     *
     * @param req
     * @param resp
     */
    private void doUpdateSelect(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String uid = req.getParameter("id");
        try {
            Admin admin = adminService.getUser(Integer.parseInt(uid));
            // 存入json格式数据
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("username", admin.getUsername());
            jsonObject.put("power", admin.getPower());
            jsonObject.put("lastTime", admin.getLastTime());
            jsonObject.put("lastIP", admin.getLastIP());
            jsonObject.put("state", admin.getState());
            jsonObject.put("id", admin.getId());
            resp.getWriter().print(jsonObject);
        } catch (ServiceException | IOException e) {
            e.printStackTrace();
            resp.getWriter().write("系统维护中");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
